package com.meiyuetao.myt.pub.web.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.core.web.SimpleController;
import lab.s2jh.core.web.json.HibernateAwareObjectMapper;
import lab.s2jh.ctx.DynamicConfigService;
import lab.s2jh.sys.service.DataDictService;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.rest.HttpHeaders;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.util.DigestUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.meiyuetao.myt.core.entity.RC4Entity;
import com.meiyuetao.myt.core.service.SolrService;
import com.meiyuetao.myt.customer.service.SsoUserService;
import com.meiyuetao.myt.ext.ExtXStream;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail.BoxOrderDetailStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetailCommodity;
import com.meiyuetao.myt.sale.service.BoxOrderDetailService;
import com.meiyuetao.myt.statistics.vo.EsBoxOrderDetailCommodityVo;
import com.meiyuetao.myt.statistics.vo.EsBoxOrderDetailVo;
import com.meiyuetao.myt.statistics.vo.EsBoxOrderVo;
import com.meiyuetao.myt.statistics.vo.EsBoxOrderVoOrderList;
import com.meiyuetao.myt.statistics.vo.EsRspVo;
import com.thoughtworks.xstream.XStream;

@MetaData("网店管家")
public class MytApiController extends SimpleController {

    @Value("${cfg.myt.logistics.url}")
    private String logisticsUrl;
    @Value("${cfg.esapi.uCode}")
    private String uCode;
    @Value("${cfg.esapi.secret}")
    private String secret;
    @Value("${cfg.rc4.key}")
    private String key;
    @Autowired
    private BoxOrderDetailService boxOrderDetailService;
    @Autowired
    private DynamicConfigService dynamicConfigService;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SolrService solrService;
    @Autowired
    private SsoUserService ssoUserService;

    public Map<String, String> getPayModeMap() {
        return dataDictService.findMapDataByPrimaryKey("IYOUBOX_FINANCE_PAY_MODE");
    }

    public HttpHeaders execute() {
        try {
            HttpServletRequest request = ServletActionContext.getRequest();
            // 接入码
            String rquestUcode = request.getParameter("uCode");
            // 方法名
            String mType = request.getParameter("mType");
            // 验证码
            String rquestSign = request.getParameter("Sign");
            // 标准时间戳
            String timeStamp = request.getParameter("TimeStamp");

            if (StringUtils.isBlank(rquestUcode)) {
                processRspInfo(new EsRspVo("0", "缺少参数：'uCode'"));
                return buildDefaultHttpHeaders();
            } else if (!uCode.equals(rquestUcode)) {
                processRspInfo(new EsRspVo("0", "错误的参数：'uCode'"));
                return buildDefaultHttpHeaders();
            }
            if (StringUtils.isBlank(mType)) {
                processRspInfo(new EsRspVo("0", "缺少参数：'mType'"));
                return buildDefaultHttpHeaders();
            }
            if (StringUtils.isBlank(rquestSign)) {
                processRspInfo(new EsRspVo("0", "缺少参数：'Sign'"));
                return buildDefaultHttpHeaders();
            }
            if (StringUtils.isBlank(timeStamp)) {
                processRspInfo(new EsRspVo("0", "缺少参数：'TimeStamp'"));
                return buildDefaultHttpHeaders();
            }
            StringBuffer signText = new StringBuffer();
            signText.append(secret);
            signText.append("mType" + mType);
            signText.append("TimeStamp" + timeStamp);
            signText.append("uCode" + rquestUcode);
            signText.append(secret);
            String sign = DigestUtils.md5DigestAsHex(signText.toString().getBytes()).toUpperCase();
            /*
             * if (!rquestSign.trim().equals(sign.trim())) { processRspInfo(new
             * EsRspVo("0", "签名无效：'Sign'")); return buildDefaultHttpHeaders(); }
             */
            if (mType.equals("mOrderSearch")) {
                // 订单列表查询
                // 周期购订单预约发货日期n天前激活导出
                // String exportDays =
                // dynamicConfigService.getString("cfg.cycleBoxOrder.exportDays",
                // "3");
                String pageSize = request.getParameter("PageSize");
                String page = request.getParameter("Page");
                String orderStatus = request.getParameter("OrderStatus");
                if (StringUtils.isBlank(orderStatus)) {
                    processRspInfo(new EsRspVo("0", "缺少参数：'OrderStatus'"));
                    return buildDefaultHttpHeaders();
                }
                String baseSql = "";
                String mytC2cShopIds = dynamicConfigService.getString("myt.c2c.shop.ids", "5");
                if (orderStatus.equals("1")) {
                    // 已付款
                    StringBuffer sb = new StringBuffer();
                    sb.append("select tab5.* from ( select bod.sn,bo.order_seq,bod.sid from iyb_box_order_detail bod,iyb_box_order bo ");
                    sb.append(" where bod.order_sid=bo.sid ");
                    sb.append(" and bod.sn is not null ");
                    sb.append(" and bo.pay_mode<>'OTHR' "); // 非货到付款
                    // + " and bod.pay_time is not null "
                    // add by harvey 15-8-4 线下闪购订单不再被网店管家抓取
                    sb.append(" AND (bo.commodity_receive_type is NULL OR bo.commodity_receive_type <> 'SELF_GET') ");
                    // 不抓取集市的订单 8-31 修正：不抓取第三方的集市的订单
                    // sb.append(" and bo.c2c_shop_info_sid IS NULL");
                    sb.append("  and (bo.c2c_shop_info_sid IS NULL or bo.c2c_shop_info_sid in (").append(mytC2cShopIds).append("))");
                    // 发货完成时间为空
                    sb.append(" and bod.delivery_finish_time is null");
                    sb.append(" and bod.order_detail_status  in ('S20PYD','S25PYD','S30C','S35C','S40DP') ");
                    sb.append(" UNION ");
                    sb.append(" select bod.sn,bo.order_seq,bod.sid from iyb_box_order_detail bod,iyb_box_order bo ");
                    sb.append(" where bod.order_sid=bo.sid ");
                    sb.append(" and bod.sn is not null ");
                    sb.append(" and bo.pay_mode='OTHR' "); // 货到付款
                    // add by harvey 15-8-4 线下闪购订单不再被网店管家抓取
                    sb.append(" AND (bo.commodity_receive_type is NULL OR bo.commodity_receive_type <> 'SELF_GET') ");
                    // 不抓取集市的订单 8-31 修正：不抓取第三方的集市的订单
                    // sb.append(" and bo.c2c_shop_info_sid IS NULL");
                    sb.append("  and (bo.c2c_shop_info_sid IS NULL or bo.c2c_shop_info_sid in (").append(mytC2cShopIds).append("))");
                    sb.append(" and bod.delivery_finish_time is null");
                    sb.append(" and bod.order_detail_status not in ('S50DF','S60R','S70CLS','S90CANCLE') ");
                    // add by harvey 15-8-4 线下闪购订单付款6小时后处理自提且未发货的订单
                    sb.append(" UNION ");
                    sb.append(" SELECT bod.sn, bo.order_seq, bod.sid ");
                    sb.append(" FROM iyb_box_order_detail bod, iyb_box_order bo ");
                    sb.append(" WHERE bod.order_sid = bo.sid ");
                    sb.append(" AND bo.pay_mode <> 'OTHR' ");
                    sb.append(" AND bo.commodity_receive_type = 'SELF_GET' ");
                    // 不抓取集市的订单 8-31 修正：不抓取第三方的集市的订单
                    // sb.append(" and bo.c2c_shop_info_sid IS NULL");
                    sb.append("  and (bo.c2c_shop_info_sid IS NULL or bo.c2c_shop_info_sid in (").append(mytC2cShopIds).append("))");
                    sb.append(" AND bod.delivery_finish_time IS NULL ");
                    sb.append(" AND bo.order_status >= 'S20PYD' ");
                    sb.append(" AND bo.order_status < 'S50DF' ");
                    sb.append(" AND DATEDIFF(hh, bo.updated_dt, GETDATE()) > 6 ");
                    sb.append(") tab5");
                    baseSql = sb.toString();
                    // +
                    // " and bod.reserve_delivery_time<=CONVERT(VARCHAR(10),dateadd(day,"
                    // + Integer.valueOf(exportDays) +
                    // ",GETDATE()),120) ) tab5";
                } else if (orderStatus.equals("0")) {
                    // 未付款
                    StringBuffer sb = new StringBuffer();
                    sb.append(" select bod.sn,bo.order_seq,bod.sid from iyb_box_order_detail bod,iyb_box_order bo ");
                    sb.append(" where bod.order_sid=bo.sid and bo.pay_mode<>'OTHR' ");
                    sb.append(" and bod.sn is not null ");
                    sb.append(" and bod.delivery_finish_time is null ");
                    sb.append(" and bod.order_detail_status  in ('S10O','S15O')");
                    baseSql = sb.toString();
                    // + " where bod.order_sid=bo.sid  "
                    // + " and bod.pay_time is null"
                    // " and bod.reserve_delivery_time<=CONVERT(VARCHAR(10),dateadd(day,"
                    // + Integer.valueOf(exportDays) + ",GETDATE()),120) ";
                } else {
                    // 问题单
                    // baseSql =
                    // " select bod.sn,bo.order_seq,bod.sid from iyb_box_order_detail bod,iyb_box_order bo "
                    // +
                    // " where bod.order_sid=bo.sid and bod.order_detail_status='S90CANCLE'";
                    // +
                    // " and bod.reserve_delivery_time<=CONVERT(VARCHAR(10),dateadd(day,"
                    // + Integer.valueOf(exportDays) + ",GETDATE()),120) " +
                    // " and bod.is_export_to_es<>1";
                    EsBoxOrderVo esBoxOrderVo = new EsBoxOrderVo("0", "1", null, page);
                    EsBoxOrderVoOrderList esBoxOrderVoOrderList = new EsBoxOrderVoOrderList();
                    esBoxOrderVo.setOrderList(esBoxOrderVoOrderList);
                    processOrderInfo(esBoxOrderVo);
                    return buildDefaultHttpHeaders();
                }

                String countSql = "select count(*) from (" + baseSql + ") tab10";
                Integer rows = jdbcTemplate.queryForInt(countSql);
                if (StringUtils.isNotBlank(pageSize) && StringUtils.isNotBlank(page)) {
                    baseSql = " select * from (SELECT TOP " + pageSize + " tab3.* FROM ( " + baseSql + " )as tab3 WHERE tab3.sid >=( " + " SELECT min(tab2.sid) "
                            + " FROM (SELECT TOP (" + pageSize + "*" + page + ") tab1.sid from ( " + baseSql + " ) as tab1 ORDER BY tab1.sid desc) tab2) "
                            + "ORDER BY sid ) tab3 order by tab3.sid desc";

                }
                final EsBoxOrderVo esBoxOrderVo = new EsBoxOrderVo(String.valueOf(rows), "1", null, page);
                EsBoxOrderVoOrderList esBoxOrderVoOrderList = new EsBoxOrderVoOrderList();
                final List<String> orderNO = new ArrayList<String>();
                jdbcTemplate.query(baseSql, new RowCallbackHandler() {
                    @Override
                    public void processRow(ResultSet rs) throws SQLException {
                        String orderSeq = rs.getString("order_seq");
                        String sn = rs.getString("sn");
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("OrderNO", orderSeq + "." + sn);
                        orderNO.add(orderSeq + "." + sn);
                    }
                });
                esBoxOrderVoOrderList.setOrderNO(orderNO);
                esBoxOrderVo.setOrderList(esBoxOrderVoOrderList);
                processOrderInfo(esBoxOrderVo);
                return buildDefaultHttpHeaders();
            } else if (mType.equals("mGetOrder")) {
                // 订单详细
                String orderNo = request.getParameter("OrderNO");
                if (StringUtils.isBlank(orderNo)) {
                    processRspInfo(new EsRspVo("0", "缺少参数：'OrderNO'"));
                    return buildDefaultHttpHeaders();
                }
                if (orderNo.indexOf(".") > -1) {
                    String orderSeq = orderNo.split("\\.")[0];
                    String sn = orderNo.split("\\.")[1];
                    if (StringUtils.isBlank(orderSeq) || StringUtils.isBlank(sn) || sn.equals("null")) {
                        processRspInfo(new EsRspVo("0", "错误的参数格式：'OrderNO'"));
                        return buildDefaultHttpHeaders();
                    }
                    GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                    groupPropertyFilter.append(new PropertyFilter(MatchType.FETCH, "boxOrder", "INNER"));
                    groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder.orderSeq", orderSeq));
                    groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "sn", sn));
                    List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
                    if (boxOrderDetails.size() == 0) {
                        processRspInfo(new EsRspVo("0", "没查询到此订单"));
                        return buildDefaultHttpHeaders();
                    } else if (boxOrderDetails.size() == 1) {
                        EsBoxOrderDetailVo esBoxOrderDetailVo = new EsBoxOrderDetailVo();
                        BoxOrderDetail boxOrderDetail = boxOrderDetails.get(0);
                        BoxOrder boxOrder = boxOrderDetail.getBoxOrder();
                        esBoxOrderDetailVo.setOrderNO(orderNo);
                        esBoxOrderDetailVo.setResult("1");
                        esBoxOrderDetailVo.setDateTime(boxOrderDetail.getCreatedDate() == null ? "" : DateUtils.formatTime(boxOrderDetail.getCreatedDate()));
                        esBoxOrderDetailVo.setBuyerID(boxOrder.getCustomerProfile().getDisplay());
                        esBoxOrderDetailVo.setBuyerName(boxOrder.getReceivePerson());
                        esBoxOrderDetailVo.setCity(boxOrder.getDeliveryCity());
                        esBoxOrderDetailVo.setProvince(boxOrder.getDeliveryProvince());
                        esBoxOrderDetailVo.setTown(boxOrder.getDeliveryStreet());
                        esBoxOrderDetailVo.setAdr(boxOrder.getDeliveryAddr());
                        esBoxOrderDetailVo.setZip(boxOrder.getPostCode());
                        esBoxOrderDetailVo.setEmail(boxOrder.getEmail());
                        esBoxOrderDetailVo.setPhone(boxOrder.getMobilePhone());
                        /*
                         * BigDecimal total = BigDecimal.ZERO; for
                         * (BoxOrderDetailCommodity item :
                         * boxOrderDetail.getBoxOrderDetailCommodities()) {
                         * total = total.add(item.getActualAmount());
                         * 
                         * }
                         */
                        Map<String, String> payModeMap = getPayModeMap();
                        String payMode = "";
                        if (boxOrder.getBoxOrderDetails().size() == 1) {
                            esBoxOrderDetailVo.setTotal(boxOrder.getActualPayedAmount());
                            if (StringUtils.isBlank(boxOrder.getPayMode())) {
                                esBoxOrderDetailVo.setPayAccount("");
                            } else {
                                payMode = boxOrder.getPayMode();
                                esBoxOrderDetailVo.setPayAccount(payModeMap.get(boxOrder.getPayMode()));
                            }
                            if (StringUtils.isBlank(boxOrder.getPayVoucher())) {
                                esBoxOrderDetailVo.setPayID("");
                            } else {
                                esBoxOrderDetailVo.setPayID(boxOrder.getPayVoucher());
                            }
                            esBoxOrderDetailVo.setPostage(String.valueOf(boxOrder.getPostage() == null ? "" : boxOrder.getPostage()));
                        } else if (boxOrder.getCircle()) {
                            esBoxOrderDetailVo.setTotal(boxOrderDetail.getActualAmount());
                            if (StringUtils.isBlank(boxOrder.getPayMode())) {
                                esBoxOrderDetailVo.setPayAccount("");
                            } else {
                                payMode = boxOrder.getPayMode();
                                esBoxOrderDetailVo.setPayAccount(payModeMap.get(boxOrder.getPayMode()));
                            }
                            if (StringUtils.isBlank(boxOrder.getPayVoucher())) {
                                esBoxOrderDetailVo.setPayID("");
                            } else {
                                esBoxOrderDetailVo.setPayID(boxOrder.getPayVoucher());
                            }
                            esBoxOrderDetailVo.setPostage(String.valueOf(boxOrderDetail.getPostage() == null ? "" : boxOrderDetail.getPostage()));
                        } else {
                            esBoxOrderDetailVo.setTotal(boxOrderDetail.getPayAmount());
                            if (StringUtils.isBlank(boxOrderDetail.getPayMode())) {
                                esBoxOrderDetailVo.setPayAccount("");
                            } else {
                                payMode = boxOrderDetail.getPayMode();
                                esBoxOrderDetailVo.setPayAccount(payModeMap.get(boxOrderDetail.getPayMode()));
                            }
                            if (StringUtils.isBlank(boxOrderDetail.getPayVoucher())) {
                                esBoxOrderDetailVo.setPayID("");
                            } else {
                                esBoxOrderDetailVo.setPayID(boxOrderDetail.getPayVoucher());
                            }
                            esBoxOrderDetailVo.setPostage(String.valueOf(boxOrderDetail.getPostage() == null ? "" : boxOrderDetail.getPostage()));
                        }
                        esBoxOrderDetailVo.setLogisticsName(boxOrderDetail.getLogisticsName());
                        String memo = boxOrder.getMemo();
                        if (memo == null) {
                            memo = "";
                        }
                        if (!Boolean.TRUE.equals(boxOrderDetail.getBuyNow())) {
                            memo = " 预订发货时间：" + DateUtils.formatDate(boxOrderDetail.getReserveDeliveryTime()) + "," + memo;
                        }
                        if ("OTHR".equals(boxOrder.getPayMode())) {
                            // 如果是货到付款，取应付金额
                            esBoxOrderDetailVo.setTotal(boxOrderDetail.getActualAmount());
                            memo = "货到付款," + memo;
                            esBoxOrderDetailVo.setChargetype("货到付款");
                        } else {
                            esBoxOrderDetailVo.setChargetype("担保交易");
                        }
                        esBoxOrderDetailVo.setCustomerRemark(boxOrder.getMemo());
                        if (StringUtils.isNotBlank(boxOrder.getInvoiceTitle())) {
                            esBoxOrderDetailVo.setInvoiceTitle(boxOrder.getInvoiceTitle());
                        } else {
                            esBoxOrderDetailVo.setInvoiceTitle("");
                        }
                        esBoxOrderDetailVo.setRemark(memo);
                        for (BoxOrderDetailCommodity bodc : boxOrderDetail.getBoxOrderDetailCommodities()) {
                            Commodity commodity = bodc.getCommodity();
                            EsBoxOrderDetailCommodityVo esBoxOrderDetailCommodityVo = new EsBoxOrderDetailCommodityVo(commodity.getErpProductId(), commodity.getTitle(),
                                    commodity.getErpSpec(), bodc.getQuantity().intValue(), bodc.getPrice());
                            esBoxOrderDetailVo.getItem().add(esBoxOrderDetailCommodityVo);
                        }
                        processOrderDetailInfo(esBoxOrderDetailVo);
                        return buildDefaultHttpHeaders();
                    } else {
                        processRspInfo(new EsRspVo("0", "订单号不唯一，查询到多条记录"));
                        return buildDefaultHttpHeaders();
                    }
                } else {
                    processRspInfo(new EsRspVo("0", "缺少参数：'OrderNO'"));
                    return buildDefaultHttpHeaders();
                }
            } else if (mType.equals("mSndGoods")) {
                // 发货通知
                String orderNo = request.getParameter("OrderNO");
                if (StringUtils.isBlank(orderNo)) {
                    processRspInfo(new EsRspVo("0", "缺少参数：'OrderNO'"));
                    return buildDefaultHttpHeaders();
                }
                if (orderNo.indexOf(".") > -1) {
                    String sndStyle = request.getParameter("SndStyle");
                    String billID = request.getParameter("BillID");
                    if (StringUtils.isBlank(sndStyle) || StringUtils.isBlank(billID)) {
                        processRspInfo(new EsRspVo("0", "缺少参数：'SndStyle'或'BillID'"));
                        return buildDefaultHttpHeaders();
                    }
                    String orderSeq = orderNo.split("\\.")[0];
                    String sn = orderNo.split("\\.")[1];
                    GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                    groupPropertyFilter.append(new PropertyFilter(MatchType.FETCH, "boxOrder", "INNER"));
                    groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder.orderSeq", orderSeq));
                    groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "sn", sn));
                    List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
                    if (boxOrderDetails.size() == 0) {
                        processRspInfo(new EsRspVo("0", "没查询到此订单"));
                        return buildDefaultHttpHeaders();
                    } else if (boxOrderDetails.size() == 1) {
                        BoxOrderDetail boxOrderDetail = boxOrderDetails.get(0);
                        BoxOrder boxOrder = boxOrderDetail.getBoxOrder();
                        if (BoxOrderDetailStatusEnum.S20PYD.equals(boxOrderDetail.getOrderDetailStatus())
                                || BoxOrderDetailStatusEnum.S25PYD.equals(boxOrderDetail.getOrderDetailStatus())
                                || BoxOrderDetailStatusEnum.S30C.equals(boxOrderDetail.getOrderDetailStatus())
                                || BoxOrderDetailStatusEnum.S35C.equals(boxOrderDetail.getOrderDetailStatus())
                                || BoxOrderDetailStatusEnum.S40DP.equals(boxOrderDetail.getOrderDetailStatus()) || "OTHR".equals(boxOrder.getPayMode())) {
                            try {
                                boxOrderDetail.setLogisticsName(sndStyle);
                                boxOrderDetail.setLogisticsNo(billID);
                                boxOrderDetailService.deliverySave(boxOrderDetail);

                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("logistics_no", boxOrderDetail.getLogisticsNo());
                                map.put("logistics_name", boxOrderDetail.getLogisticsName());
                                map.put("delivery_city", boxOrder.getDeliveryCity());
                                String deliveryStr = JSONObject.toJSONString(map);
                                String params = RC4Entity.encry_RC4_string(deliveryStr, key);
                                postToMyt(params);
                            } catch (Exception e) {
                                processRspInfo(new EsRspVo("0", e.getMessage()));
                                return buildDefaultHttpHeaders();
                            }
                            processRspInfo(new EsRspVo("1", null));
                            return buildDefaultHttpHeaders();
                        }
                        processRspInfo(new EsRspVo("0", "订单不具发货条件"));
                        return buildDefaultHttpHeaders();
                    } else {
                        processRspInfo(new EsRspVo("0", "订单号不唯一，查询到多条记录"));
                        return buildDefaultHttpHeaders();
                    }
                } else {
                    processRspInfo(new EsRspVo("0", "无效订单号"));
                    return buildDefaultHttpHeaders();
                }
            } else {
                processRspInfo(new EsRspVo("0", "无效的方法"));
                return buildDefaultHttpHeaders();
            }
        } catch (NumberFormatException e) {
            processRspInfo(new EsRspVo("0", e.getMessage()));
            return buildDefaultHttpHeaders();
        }
    }

    /**
     * 订单快递信息
     * 
     * @param paramsValue
     */
    private void postToMyt(String paramsValue) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(logisticsUrl);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("Params", paramsValue));
        String response = null;
        try {
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                response = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println("logistics Response：" + response);
            }
            httpClient.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean flag = false;
        if (StringUtils.isNotBlank(response)) {
            ObjectMapper objectMapper = HibernateAwareObjectMapper.getInstance();
            Map<String, String> statusMap = new HashMap<String, String>();
            try {
                statusMap = objectMapper.readValue(response, Map.class);
                if (String.valueOf(statusMap.get("Code")).equals("10")) {
                    flag = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (flag) {
            System.out.println("发货成功");
        } else {
            System.out.println("发货失败");
        }
    }

    public String getuCode() {
        return uCode;
    }

    public void setuCode(String uCode) {
        this.uCode = uCode;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    private void processOrderInfo(EsBoxOrderVo esBoxOrderVo) {
        XStream xstream = ExtXStream.createXstream(EsBoxOrderVo.class);
        xstream.processAnnotations(EsBoxOrderVo.class);
        String xmlhead = "<?xml version=\"1.0\" encoding=\"gbk\"?>\n";
        String xmlinfo = xmlhead + xstream.toXML(esBoxOrderVo);
        setHttpServletResponse(xmlinfo);
    }

    private void processOrderDetailInfo(EsBoxOrderDetailVo esBoxOrderDetailVo) {
        XStream xstream = ExtXStream.createXstream(EsBoxOrderDetailVo.class);
        xstream.processAnnotations(EsBoxOrderDetailVo.class);
        String xmlhead = "<?xml version=\"1.0\" encoding=\"gbk\"?>\n";
        String xmlinfo = xmlhead + xstream.toXML(esBoxOrderDetailVo);
        setHttpServletResponse(xmlinfo);
    }

    private void processRspInfo(EsRspVo esRspVo) {
        XStream xstream = ExtXStream.createXstream(EsRspVo.class);
        xstream.processAnnotations(EsRspVo.class);
        String xmlhead = "<?xml version=\"1.0\" encoding=\"gbk\"?>\n";
        String xmlinfo = xmlhead + xstream.toXML(esRspVo);
        setHttpServletResponse(xmlinfo);
    }

    private void setHttpServletResponse(String xmlinfo) {
        HttpServletResponse response = getResponse();
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("gbk");
        try {
            response.getWriter().print(xmlinfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public HttpHeaders webRootDir() {
        setModel(ServletActionContext.getServletContext().getRealPath("/"));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders chinaBabyNew() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String begin = request.getParameter("begin");
        String end = request.getParameter("end");
        if (StringUtils.isBlank(begin) || StringUtils.isBlank(end)) {
            processRspInfo(new EsRspVo("0", "缺少参数：'begin' or 'end'"));
            return buildDefaultHttpHeaders();
        }
        int beginNo = Integer.valueOf(begin);
        int endNo = Integer.valueOf(end);
        if (endNo < beginNo) {
            processRspInfo(new EsRspVo("0", "参数错误：'begin' or 'end'"));
            return buildDefaultHttpHeaders();
        }
        String msg = "";
        for (int i = beginNo; i <= endNo; i++) {
            msg += String.valueOf(i) + ";";
            ssoUserService.chinaBabyRegister(String.valueOf(i));
        }
        setModel(msg);
        return buildDefaultHttpHeaders();
    }

}